﻿// News Framework
// (C) Tanzim Saqib. Oct 25, 2010.
// http://TanzimSaqib.com | http://newsfx.codeplex.com

namespace TanzimSaqib.NewsFramework
{
    using System.Xml.Serialization;
    using System.IO;
    using System;
    using System.IO.IsolatedStorage;

    internal sealed class StorageHelper
    {
        public static void ClearCache()
        {
            var fileNames = new[] { FxConstants.FeedItemsXmlFileName, FxConstants.RSSItemsXmlFileName };

            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                foreach (var fileName in fileNames)
                {
                    try
                    {
                        appStorage.DeleteFile(fileName);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }

        public static void SaveFile<T>(string fileName, T collection)
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = appStorage.OpenFile(fileName, FileMode.Create))
                {
                    using (var writer = new StreamWriter(file))
                    {
                        var serializer = new XmlSerializer(typeof(T));
                        serializer.Serialize(writer, collection);
                        writer.Close();
                    }
                    
                    file.Close();
                }
            }
        }

        public static T ReadFile<T>(string fileName) where T : new()
        {
            var collection = new T();

            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read, appStorage))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var serializer = new XmlSerializer(typeof(T));
                        collection = reader.EndOfStream ? new T() : (T)serializer.Deserialize(reader);

                        reader.Close();
                        stream.Close();
                    }
                }
            }

            return collection;
        }
    }
}
